﻿using ConfExpert.Forms.Depo;
using DevTeam;
using System;
using System.Data;
using System.Linq;

namespace ConfExpert.Forms.ImportWizards
{
    public partial class XITopCekiListesi : XImportWizard
    {
        int YuklemeId;
        public XITopCekiListesi(int YuklemeId)
        {
            InitializeComponent();
            this.YuklemeId = YuklemeId;

            this.ProcessStart += XITopCekiListesi_ProcessStart;
            this.ProcessDone += XITopCekiListesi_ProcessDone;
            btnSave.ItemClick += BtnSave_ItemClick;
        }

        public XITopCekiListesi()
        {
            //placeholder
        }

        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            DataSet ds = MasterGrid.Dataset();
            if (ds.Tables[0].Select("ProductId is null").Length > 0)
            {
                ShowErrorMessage("ProductId lerin tamamı dolu olmalı!");
                return;
            }

            string str1 = ds.Tables[0].Serialize();
            string str2 = ds.Tables[1].Serialize();

            int res = ExecuteScalar("UpdYuklemeTopBilgileri2", YuklemeId, /*idxs,*/ str1, str2).ToInt();       //DİKKAT!
            if (res > 0)
            {
                Notify("Yüklemeye ilişkin top bilgileri sisteme aktarıldı.");
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
                ShowErrorMessage("Yükleme ve dosyadaki artikeller uyuşmuyor!");

        }

        void XITopCekiListesi_ProcessDone()
        {
            var distinctValues = Article.AsEnumerable().Select(row => new { Kod = row.Field<string>("Article"), }).Distinct().ToList();
            string codes = string.Join(",", Array.ConvertAll(distinctValues.ToArray(), i => i.Kod));

            DataTable dtId = Session.DataManager.ExecuteDataTable("GetProductIdByCode", codes);
            foreach (DataRow drArticle in Article.Rows)
            {
                DataRow[] drIds = dtId.Select("Kod='" + drArticle["Article"] + "'");
                if (drIds.Length == 1)
                {
                    drArticle["ProductId"] = (int)drIds[0]["ProductId"];
                }
            }
            /*
             * 
            DataTable dtId = AppSession.DataManager.ExecuteDataTable("GetProductIdByCode2", codes);
            foreach (DataRow drArticle in Article.Rows)
            {
                DataRow[] drIds = dtId.Select("Kod='" + drArticle["Article"] + "'");
                if (drIds.Length == 1)
                    drArticle["ProductId"] = (int)drIds[0]["ProductId"];
            }
             * 
             * DESTEX_AF_1 için!
             */

            MasterGrid.Init(Article);
            MasterGrid.AddDetailGrid(DetailGrid, "Article");
            MasterGrid.AddColumn("TotalQty", typeof(decimal), "SUM(Child({FK}).Qty)");
            MasterGrid.AddColumn("RollCount", typeof(int), "COUNT(Child({FK}).Article)");
            DetailGrid.MakeColumnInvisible("Article");
            MasterGrid.YanYanaGetir("TotalQty:CustomerCode");

            MasterGrid.AddSummary("TotalQty", "RollCount");
            DetailGrid.AddSummary("Qty");

            MasterGrid.MakeReadOnly("ProductId");
            DetailGrid.MakeReadOnly();

            MasterGrid.SetViewCaption("Artikeller");
            DetailGrid.SetViewCaption("Toplar");

            DetailGrid.Columns["Qty"].Width = 100;
            DetailGrid.BestFitColumns();
            MasterGrid.BestFitColumns();

            Kontrol();
        }

        void XITopCekiListesi_ProcessStart()
        {
            Result = new DataSet();
            Article = new DataTable();
            Roll = new DataTable();
            Result.Tables.Add(Article);
            Result.Tables.Add(Roll);

            Article.Columns.Add("ProductId", typeof(int));
            Article.Columns.Add("Article", typeof(string));
            Article.Columns.Add("CustomerCode", typeof(string));
            Article.Columns.Add("VendorCode", typeof(string));
            Article.Columns.Add("VendorConstruction", typeof(string));
            Article.Columns.Add("CurrentConstruction", typeof(string));
            //dtArt.Columns.Add("AcceptedConstruction", typeof(string));

            Roll.Columns.Add("VendorRollId", typeof(long));
            Roll.Columns.Add("LotNo", typeof(string));
            Roll.Columns.Add("Qty", typeof(decimal));
            Roll.Columns.Add("WidthActual", typeof(decimal));
            Roll.Columns.Add("WidthUsable", typeof(decimal));
            Roll.Columns.Add("Article", typeof(string));
            Roll.Columns.Add("Kalite2", typeof(string));
            //Roll.Columns.Add("RowIndex", typeof(int));
            //Roll.Columns.Add("OrderNo", typeof(string));
        }


        public DataTable Article;
        public DataTable Roll;
        public DataSet Result;

        public void Kontrol()
        {
            bool res = false;
            DataTable Prd = new DataTable();

            DataSet d = ExecuteDataSet("CheckTopCeki", YuklemeId, Article.Serialize());
            if (d.Tables.Count > 0)
            {
                btnSave.Enabled = false;

                using (ArtikelMetrajEsleme popup = new ArtikelMetrajEsleme(d))
                    if (popup.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Prd = popup.d.Tables[1];
                        btnSave.Enabled = true;
                        res = true;
                    }
            }

            if (res)
            {
                foreach (DataRow r in Prd.Rows)
                    MasterGrid.DataTable().Select("Article='" + r["Article"] + "'")[0]["ProductId"] = r["ProductId"];

                MasterGrid.RefreshData();
            }
        }

        private void XITopCekiListesi_Load(object sender, EventArgs e)
        {
            btnProcessFile.PerformClick();
        }
    }
}
